const qs = require('querystringify')
const Db = require('./db.js')

class Article extends Db {
  getList(obj) {
    let { whereStr, limit } = super.getSql(obj),
    q = whereStr.replace('cid', 'classify_id')
    let sql = `SELECT * FROM t_web_article a WHERE is_use = 1 AND is_public = 1 ${q} ORDER BY a.sort asc,a.create_time DESC ${limit}`
    let sql1 = `SELECT count(*) FROM t_web_article WHERE is_use = 1 AND is_public = 1 ${q}`
    return Promise.all([super.query(sql, ''), super.query(sql1, '')]).then(([res1, res2]) => {
      return {
        data: this.filterArticles(res1),
        count: res2[0]['count(*)']
      }
    }).catch(super.handleError)
  }
  getDetail(id) {
    let sql = `SELECT * FROM t_web_article where is_use = 1 AND is_public = 1 AND model = 3 AND  id = ${id}`
    return super.query(sql, '').then(res => res[0]).then(data => {
      let sql1 = `SELECT a.id FROM t_web_article a WHERE is_use = 1 AND is_public = 1 AND classify_id = ${data.classify_id} AND model = 3 ORDER BY a.sort asc,a.create_time DESC`
      // let sql1 = `select a.id from t_web_article a left join t_web_classify b on a.classify_id = b.id where a.classify_id = ${data.classify_id} and b.is_use = 1 and a.model = ${data.model} and a.is_use = 1 and a.is_public = 1 order by a.sort asc, a.create_time desc`
      return super.query(sql1, '').then(res1 => {
        let ids = res1.map(item => +item.id)
        let idx = ids.indexOf(+id)
        if (idx === 0) {
          data.previous_id = 0
        } else {
          data.previous_id = ids[idx - 1]
        }
        if (idx === (ids.length - 1)) {
          data.next_id = 0
        } else {
          data.next_id = ids[idx + 1]
        }
        return data
      }).catch(super.handleError)
    }).catch(super.handleError)
  }
  filterArticles(t) {
    return t.map(item => {
      item.content_mini = item.content.replace(/<\/?.+?>/g, '').replace(/ /g, '').substring(0, 80)
      item.hits_compute = item.hits_base + item.hits
      item.create_time = this.transfereTime(item.create_time)
      item.public_time = this.transfereTime(item.public_time)
      return item
    })
  }
  transfereTime(time) {
    // yyyy-MM-dd'T'HH:mm:ss.SSSZ
    // const timeReg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}).(\d{3})Z/
    // return time.replace(timeReg, `${year}/${month}/${day} ${hour}:${minute}:${second}`)
    let year = time.getFullYear()
    let month = time.getMonth()
    let day = time.getDay()
    let hour = time.getHours()
    let minute = time.getMinutes()
    let second = time.getSeconds()
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`
  }
}

module.exports = new Article()